package com.sgu6.sgu6_machine.util;

import android.os.Environment;

import com.sgu6.redis.dto.ListGoodsSimpleDto;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.List;

public class GoodsUtils {

    private static final String TAG = GoodsUtils.class.getSimpleName();
    private static final String FILE_PATH = Environment.getExternalStorageDirectory().getPath() + "/sgu6/goods/";
    private static File file;

    static {
        //如果文件不存在就创建文件
        File tempFile = new File(FILE_PATH);
        if (!tempFile.exists()) {
            tempFile.mkdir();
        }
        file = new File(FILE_PATH, "goods.txt");
        if (!file.exists()) {
            try {
                file.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static void write(List<ListGoodsSimpleDto> goodsSimpleDtos) {
        ObjectOutputStream oos = null;
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(file);
            //获取输出流
            //这里如果文件不存在会创建文件，这是写文件和读文件不同的地方
            oos = new ObjectOutputStream(fos);
            //获取输入框内的文件进行写入
            //这里不能再用普通的write的方法了
            //要使用writeObject
            oos.writeObject(goodsSimpleDtos);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (fos != null) {
                    fos.close();
                }

                if (oos != null) {
                    oos.close();
                }
            } catch (IOException e) {
            }

        }
    }


    public static List<ListGoodsSimpleDto> read() {
        ObjectInputStream ois = null;
        FileInputStream fis = null;
        try {
            fis = new FileInputStream(file);
            //获取输入流
            ois = new ObjectInputStream(fis);
            //获取文件中的数据
            Object goods = ois.readObject();
            //把数据显示在TextView中
            return (List<ListGoodsSimpleDto>) goods;
        } catch (Exception e) {
            e.printStackTrace();
            return new ArrayList<ListGoodsSimpleDto>();
        } finally {
            try {
                if (ois != null) {
                    ois.close();
                }
                if (fis != null) {
                    fis.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}
